import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Input, Space, Spin, Table, Tree,Popconfirm ,Upload,message} from 'antd';
import Api from '../../../../../utils/api';

import dynamicColumnXzqyApi from '../../../../../utils/apis/dynamicColumnXzqyApi';
import XzqhApi from '../../../../../utils/apis/XzqhApi';
import _ from 'lodash';
import ScrollTable from '../../../../common/ScrollTable';
import { logDOM } from '@testing-library/react';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import FetchHelper from '../../../../../utils/helper/fetch-helper';
import { UploadOutlined } from '@ant-design/icons';


export default function Xzqh() {
    const [gxData, setGxData] = useState(true);
    const [xzqhData, setXzqhData] = useState();
    const [total, setTotal] = useState();
    const [allColumns, setAllColumns] = useState();
    const [loading, setLoading] = useState();
    const rootRef = useRef();
    const [params,setParams]=useState({
        pageSize:10,
        pageNum:1,
        //xzqhdl:'行政区划'
    })


    useEffect(() => {
        dynamicColumnXzqyApi.xzqh().then(data => {
            setAllColumns(data);
        })
    }, [])

    // useEffect(() => {
    //     dynamicColumnXzqyApi.xzqh().then(data => {
    //         setAllColumns(data);
    //     })
    // }, [])
const [value,setValue]=useState()
    useEffect(() => {
        if (params) {
            setLoading(true)
            XzqhApi.list(params).then(resp => {
                if(value){
                    const filterData=resp?.rows.filter(item=>item?.mc.includes(value))
                    setXzqhData(filterData)
                }else{
                    setXzqhData(resp.rows)
                }
                
                setTotal(resp.total);
            }).finally(e => {
                setLoading(false)
            })

        }
    }, [params,value,gxData])
    //数据下载
    const url = '/admin-api/ybyj/xzqh/export';
    // const tableCols = allColumns?.[params.qmc || params.mc] || [];
    //搜索
    const onSearch=(value)=>{
        setValue(value);
        setParams(params=>{
            return{
                ...params,
                mc:value,
                pageNum:1
            }
        })
    }
    const history=useHistory()
    //新增
    const addXzqh=(key)=>{
        history.push(`/manager/xzqhAdd`)
    }
    //查看
    const xzqhHandleLook=(record)=>{
        history.push(`/manager/xzqhLook/${record.id}`)
    }
    //修改
    const xzqhHandleEdit=(record)=>{
        history.push(`/manager/xzqhEdit/${record.id}`)
    }
    //删除
    const xzqhHandleDelete=(record)=>{
        const newXzqhData=xzqhData.filter(function (arr){
            return arr.id!==record.id
        })
        FetchHelper.deleteJson(`/admin-api/ybyj/xzqh/`+record.id).then(() => alert('删除成功')).catch(error => alert("删除失败") + error)
        setXzqhData(newXzqhData)
    }
    const props={
        name: 'file',
        action: '/admin-api/ybyj/xzqh/import',
        headers: {
            authorization: 'authorization-text',
        },
        beforeUpload(file) {
            const isValidFormat = file.type === 'application/vnd.ms-excel';
            

            if (!isValidFormat) {
                message.error('只能上传 .xls格式的文件!');
            }
          

            return isValidFormat 
        },
        onChange(info) {
            console.log('node', info)
            if (info.file.status === 'done') {
                if (info.file.response.code !== 200) {
                    message.error( <>
                        {info.file.name} 文件上传失败！<br />
                        错误代码：{info.file.response.msg}<br />
                        可能原因：数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后再进行上传
                    </>);
                } else {
                    message.success(`${info.file.name} 文件上传成功`);
                    //触发组件更新
                    setGxData(!gxData)
                }

            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
                message.warning(`数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后再进行上传`);
            }
        },
    }
    return <div className='layout-h h100'>

        <Card size="small" className='h100 fill w0' style={{
            position: "relative",
        }} bodyStyle={{

            display: "flex",
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>
                <Space>
                    <Button type="primary" onClick={addXzqh}>新增</Button>
                    <Upload {...props}>
                            <Button icon={<UploadOutlined />}>数据导入</Button>
                        </Upload>
                    {/* <Button onClick={() => fetch(url, {
                        method: 'POST',

                        headers: {
                            'Content-Type': "application/json;charset=UTF-8",
                        }
                    }).then(response => response.blob()).then(blob => {
                        const a = document.createElement("a");
                        a.download = "data.xls";
                        a.href = URL.createObjectURL(blob);
                        a.click();
                    }).catch(error => console.log(error))}>数据导出</Button> */}
                </Space>

                <div>
                    <Input.Search placeholder='输入名称查找'
                    allowClear
                    enterButton={true}
                    onSearch={(value) => {
                        setParams(params => {
                            return {
                                ...params,
                                mc: value,
                                pageNum: 1
                            }
                        })
                    }}
                    />
                </div>
            </div>

            {/* {loading && <div style={{
                position: 'absolute',
                left: 0,
                bottom: 0,
                right: 0,
                top: 0,
                display: 'flex',
                alignItems: "center",
                justifyContent: "center"
            }}>
                <Spin />
            </div>} */}
            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{
                    
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={xzqhData}
                    // scroll={{
                    //     x: 320 + _.sumBy(tableCols, 'width'),
                    // }}
                    columns={[
                        // {
                        //     title: '责任人',
                        //     dataIndex: 'zrr',
                        //     fixed: 'left',
                        //     width: 160
                            
                        // },
                        // {
                        //     title: '责任人电话',
                        //     dataIndex: 'zrrdh',
                        //     fixed: 'left',
                        //     width: 160
                            
                        // },
                       
                        {
                            title: '名称',
                            dataIndex: 'mc',
                           
                            width: 160
                            
                        },
                        {
                            title: '编码',
                            dataIndex: 'bm',

                            width: 160
                            
                        },
                        {
                            title: '全名称',
                            dataIndex: 'qmc',
                           
                            width: 160
                            
                        },
                        {
                            title: '全编码',
                            dataIndex: 'qbm',
                           
                            width: 160
                            
                        },
                        {
                            title: '级别',
                            dataIndex: 'jb',
                           
                            width: 160
                            
                        },
                       
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            render: (text, record) => {
                                return <Space size="middle">
                                    <Button onClick={e => {xzqhHandleLook(record)}}>查看</Button>

                                    <Button onClick={e => {xzqhHandleEdit(record)}}>编辑</Button>
                                    <Popconfirm title="确定删除吗?" onConfirm={e => xzqhHandleDelete(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </Space>

                            }
                        }
                        
                        // ...tableCols
                    ].map(item => {
                        return {
                            ...item,
                           
                        }
                    })}
                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,

                    }}
                   onChange={({current})=>{
                    setParams(params=>{
                        return {
                            ...params,
                            pageNum:current
                        }
                    })
                   }}

                />}
            </div>
        </Card>
    </div>;


}

